const jsonwebtoken = require('jsonwebtoken');
const Router = require('koa-router')
const { checkTopicExist } = require('../controllers/topics');
const { checkAnswerExist } = require('../controllers/answers');
const jwt = require('koa-jwt')
const router = new Router({
  prefix: '/users'
});

const {
  find,
  findById,
  create,
  update,
  delete: del,
  login,
  checkOwner,
  checkUserExist,
  follow,
  listFollowing,
  listFollowers,
  unfollow,
  followTopic,
  unfollowTopic,
  listFollowingTopics,
  listQuestions,
  listLikingAnswers, likeAnswer, unlikeAnswer, listDislikingAnswers, dislikeAnswer, undislikeAnswer,
  listCollectingAnswers, collectAnswer, uncollectAnswer,
} = require('../controllers/users')

const { secret } = require('../config');
// const auth = async (ctx, next) => {
//   // header里面都是小写
//   const { authorization = '' } = ctx.request.header;
//   const token = authorization.replace('Bearer ', '')
//   try {
//     const user = jsonwebtoken.verify(token, secret)
//     ctx.state.user = user
//   } catch (error) {
//     ctx.throw(401, error.message)
//   }
//   await next()
// }
const auth = jwt({ secret })


router.get('/', find);

router.post('/', create);

router.get('/:id', findById);

router.patch('/:id', auth, checkOwner, update);

router.delete('/:id', auth, checkOwner, del);

router.post('/login', login)

// 列出用户的关注者列表
router.get('/:id/following', listFollowing);

// 关注某个用户
router.put('/following/:id', auth, checkUserExist, follow);

// 取关某个用户
router.delete('/following/:id', auth, checkUserExist, unfollow);

// 获取某个用户的粉丝列表
router.get('/:id/followers', listFollowers);

// 关注话题
router.put('/followingTopics/:id', auth, checkTopicExist, followTopic);

// 取关话题
router.delete('/followingTopics/:id', auth, checkTopicExist, unfollowTopic);

// 获取某个用户关注的话题列表
router.get('/:id/followingTopics', listFollowingTopics);

// 某个用户的所有提问的问题列表
router.get('/:id/questions', listQuestions);

// 指定用户所赞过的答案列表
router.get('/:id/likingAnswers', listLikingAnswers);

// 赞一个答案
router.put('/likingAnswers/:id', auth, checkAnswerExist, likeAnswer, undislikeAnswer);


// 指定用户所踩过的答案列表
router.get('/:id/dislikingAnswers', listDislikingAnswers);

// 踩一个答案(自动取消赞了)
router.put('/dislikingAnswers/:id', auth, checkAnswerExist, dislikeAnswer, unlikeAnswer);

// 取消踩这个答案
router.delete('/dislikingAnswers/:id', auth, checkAnswerExist, undislikeAnswer);

// 取消赞这个答案
router.delete('/likingAnswers/:id', auth, checkAnswerExist, unlikeAnswer);


// 列出用户的收藏的答案列表
router.get('/:id/collectingAnswers', listCollectingAnswers);

// 用户收藏答案
router.put('/collectingAnswers/:id', auth, checkAnswerExist, collectAnswer);

// 用户取消收藏答案
router.delete('/collectingAnswers/:id', auth, checkAnswerExist, uncollectAnswer);

module.exports = router